package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author Lenovo
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-06-06 14:04:03
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public Result login(LoginVo loginVo) {

        //--1验证码验证
        String key = "login-"+loginVo.getMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        if(redisCode==null){
            return Result.error().setMsg("验证码已过期");
        }
        if(!redisCode.equals(loginVo.getCode())){
            return Result.error().setMsg("验证码错误");
        }
        //--2.获取用户信息
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginVo.getMobile()));
        if(tbUser==null){
            return Result.error().setMsg("用户不存在");
        }
        //--4.生成token并返回
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", tbUser.getUserId()).compact();

        String tokenKey = "token-"+tbUser.getUserId();

        redisTemplate.opsForValue().set(tokenKey,token,60,TimeUnit.MINUTES);

        tbUser.setToken(token);
        return Result.ok().setData(tbUser);
    }

    @Override
    public Result sendCode(String mobile) {

        //--0.验证手机号
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, mobile));
        if(tbUser==null){
            tbUser = new TbUser();
            tbUser.setUserMobile(mobile);
            tbUser.readyCreate(null);
            tbUserMapper.insert(tbUser);

        }
        //生成验证码
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码:"+code);
        //保存验证码并发送
        String key = "login-" + mobile;

        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);

        MobileMessageUtil.sendMobileMessage(mobile,code);

        return Result.ok().setData(code);
    }
}




